package com.schoolcloud.social.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.api.client.front.FrontUserClient;
import com.schoolcloud.common.model.UserInfo;
import com.schoolcloud.common.util.UserContext;
import com.schoolcloud.social.dto.PrivateMessageSaveDTO;
import com.schoolcloud.social.entity.ConversationParticipants;
import com.schoolcloud.social.entity.Conversations;
import com.schoolcloud.social.service.ConversationParticipantsService;
import com.schoolcloud.social.mapper.ConversationParticipantsMapper;
import com.schoolcloud.social.service.ConversationsService;
import com.schoolcloud.social.service.PrivateMessageService;
import com.schoolcloud.social.vo.ConversationInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hongmizfb
 * @description 针对表【conversation_participants(会话参与者)】的数据库操作Service实现
 * @createDate 2025-04-27 15:32:48
 */
@Service
@RequiredArgsConstructor
public class ConversationParticipantsServiceImpl extends ServiceImpl<ConversationParticipantsMapper, ConversationParticipants>
        implements ConversationParticipantsService {

    private final PrivateMessageService privateMessageService;
    private final ConversationsService conversationsService;
    private final FrontUserClient frontClient;


    @Override
    public List<ConversationInfoVO> getConversationListByUserId(String userId) {
//        查询参与者表，筛选出当前用户的所有会话
        List<ConversationParticipants> list = lambdaQuery().eq(ConversationParticipants::getUserId, userId).list();
        if (CollUtil.isEmpty(list)){
            return null;
        }
        return list.stream().map(item -> {
            ConversationInfoVO vo = new ConversationInfoVO();
            Conversations byId = conversationsService.getById(item.getConversationId());
            BeanUtils.copyProperties(byId, vo);
            vo.setLastMessage(privateMessageService.getById(byId.getLastMessageId()));
            vo.setUnreadCount(item.getUnreadCount());
            if (byId.getIsGroup() == 0) {
                //            查询会话参与的另一个参与者
                ConversationParticipants other = lambdaQuery().eq(ConversationParticipants::getConversationId, byId.getConversationId()).ne(ConversationParticipants::getUserId, userId).one();
                UserInfo data = frontClient.getFroUserInfoById(other.getUserId().toString()).getData();
                vo.setOtherAvatar(data.getAvatar());
                vo.setOtherNickname(other.getNickname());
                vo.setOtherUserId(other.getUserId().toString());
            }
            return vo;
        }).toList();
    }

    @Override
    public void createMessage(PrivateMessageSaveDTO dto) {
//        查询用户是否存在相关会话(直接查询用户所有参与的会话表，然后查询这些会话表是否存在传入的这类会话）
        Integer conversationId = dto.getConversationId();
        Conversations system = null;
        if (conversationId == null) {
            List<Integer> conversationIds = lambdaQuery().eq(ConversationParticipants::getUserId, UserContext.getUserToInteger())
                    .list().stream().map(ConversationParticipants::getConversationId).toList();
            if (CollUtil.isNotEmpty(conversationIds)) {
                system = conversationsService.lambdaQuery()
                        .eq(dto.getType().equals("notice"),Conversations::getCreatorType, "system")
                        .eq(dto.getType().equals("private"),Conversations::getCreatorType, "user")
                        .eq(Conversations::getSourceType, dto.getSourceType()).
                        in(Conversations::getConversationId, conversationIds).one();
            }
        }
        else {
            system = conversationsService.getById(conversationId);
        }
        if (system == null) {
//            创建一个会话
            Conversations conversations = new Conversations();
            if (dto.getType().equals("notice")){
                conversations.setCreatorType("system");
            }
            else if (dto.getType().equals("private")){
                conversations.setCreatorType("user");
            }
            conversations.setSourceType(dto.getSourceType().getKey());
            conversations.setSourceId(dto.getSourceId());
            conversations.setIsGroup(0);
            conversations.setIsActive(0);
            conversations.setStatus(0);
            conversations.setCreateTime(LocalDateTime.now());
            conversationsService.save(conversations);
            system = conversations;
//            设置会话参与者
            ConversationParticipants receiver = new ConversationParticipants();
            receiver.setUserId(dto.getReceiverId());
            receiver.setConversationId(system.getConversationId());
//            如果是私聊，则设置昵称
            if (dto.getType().equals("private")){
                UserInfo data = frontClient.getFroUserInfoById(dto.getReceiverId().toString()).getData();
                receiver.setNickname(data.getUserName());
            }
            receiver.setUnreadCount(1);
            receiver.setStatus(0);
            receiver.setIsPinned(0);
            save(receiver);
//            设置发送者,
            ConversationParticipants sender = new ConversationParticipants();
            if (dto.getType().equals("notice")){
                sender.setNickname(dto.getSourceType().getMsg());
                UserInfo froUser = new UserInfo();
                froUser.setUserName(dto.getSourceType().getKey());
                UserInfo data = frontClient.getUser(froUser).getData();
                sender.setUserId(data.getUserId());
            }
            else if (dto.getType().equals("private")){
                UserInfo data = frontClient.getFroUserInfoById(UserContext.getUser()).getData();
                sender.setUserId(data.getUserId());
                sender.setNickname(data.getNickname());
            }
            sender.setConversationId(system.getConversationId());
            sender.setUnreadCount(0);
            sender.setStatus(0);
            save(sender);
        }
//            直接使用会话即可,然后保存该信息
        dto.setConversationId(system.getConversationId());
        privateMessageService.save(dto);
//            查询这个会话的参与记录,修改该会话的未读消息数量
        ConversationParticipants conversationParticipants = lambdaQuery().eq(ConversationParticipants::getConversationId, system.getConversationId()).eq(ConversationParticipants::getUserId, dto.getReceiverId()).one();
        conversationParticipants.setUnreadCount(conversationParticipants.getUnreadCount() + 1);
        updateById(conversationParticipants);
        Conversations conversations = new Conversations();
        conversations.setConversationId(system.getConversationId());
        conversations.setLastMessageId(dto.getMessageId());
        conversations.setLastMessageTime(LocalDateTime.now());
        conversationsService.updateById(conversations);
    }
}




